<?php
namespace app\common\model;

use think\Exception;
use think\model\concern\SoftDelete;
use app\api\controller\WxpayController;
use app\common\model\FinancialRecord as Fin;

class Order extends Base
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    /**
     * 订单列表
     */
    public static function getOrderList($userId, $status, $page = 1)
    {
        $model = self::where(['user_id' => $userId]);
        if($status >= 0) $model = $model->where('status', $status);

        $list = $model
            ->field('id, order_no, shop_id as shop_name, price, goods_list, status')
            ->limit(($page - 1) * 20, 20)
            ->order('status DESC, create_time DESC')
            ->select();

        if(!$list) return false;
        return $list;
    }

    /**
     * 订单支付
     */
    public static function orderPay($userId, $orderId)
    {
        $orderInfo = self::getFind(['id' => $orderId]);
        $orderNo = getOrderNo();
        self::edit(['id' => $orderId, 'order_no' => $orderNo]);

        $payData['openid']    = User::getVal(['id' => $userId], 'openid');
        $payData['order_no']  = $orderNo;
        $payData['total_fee'] = $orderInfo['price'];
        $payData['body']      = Shop::getVal(['id' => $orderInfo['shop_id']], 'name') ?? '磊善';
        $payData['notify']    = 'notify';

        $payController = new WxpayController();
        $payBackData   = $payController->pay($payData);

        if($payBackData['code'] == 400) return $payBackData['return_msg'];
        return $payBackData['sign'];
    }

    public function getGoodsListAttr($val)
    {
        return json_decode($val);
    }

    public function getStatusAttr($val)
    {
        $status = [0 => '待支付', 1 => '待发货', 2 => '待收货', 3 => '已完成', 4 => '已取消'];
        return $status[$val];
    }

    public function getShopNameAttr($val)
    {
        return Shop::getVal(['id' => $val], 'name');
    }

    /**
     * 订单支付回调
     */
    public function orderPayNotify($orderNo = '')
    {
        $orderInfo = self::where('order_no', $orderNo)->find();
        $goodsList = json_decode($orderInfo['goods_list'], true);

        $orderId = $orderInfo['id'];

        self::beginTrans();
        try {
            /** 修改订单状态 */
            if(self::edit(['id' => $orderId, 'status' => 1, 'pay_time' => time()]) === false) throw new Exception('订单状态修改失败！');

            foreach($goodsList as $k => $info){
                switch ($info['type']) {
                    case '普通商品':
                        # code...
                        break;
                    case '佣金商品':
                        if($orderInfo['is_brokerage'] == 0){
                            /** 用户增加佣金 */
                            if(User::setIncField(['id' => $orderInfo['user_id']], 'money_brokerage', $info['rebate_brokerage']) === false) throw new Exception('佣金增加失败，请稍后重试！');
                            if(Fin::adds($orderInfo['user_id'], $orderInfo['id'], 2, 1, '商品返利', $info['rebate_brokerage']) === false) throw new Exception('添加财务记录失败！');

                            /** 发放推荐奖 */
                            if(User::pushAward($orderInfo['user_id'], $orderInfo['price'], $orderInfo['id']) === false) throw new Exception('培育佣金发放失败！');
                        }
                        break;
                    case '红包商品':
                        if($orderInfo['is_money_red'] == 0){
                            
                        }
                        break;
                    case '积分商品':
                        # code...
                        break;
                    case '健康币商品':
                        # code...
                        break;
                    
                    default:
                        return 'fail';
                        break;
                }
            }

            self::commitTrans();
        } catch (\Throwable $e) {
            self::rollbackTrans();
            return false;
        }
    }
}